home *** CD-ROM | disk | FTP | other *** search
- The C programs hex.c and unhex.c translate between 8-bit binary files
- and straight hex files, in which every pair of hexadecimal digits corresponds
- to a single 8-bit byte. Certain files in the Kermit distribution are in
- this format. You can recognize them because they contain only the characters
- 0-9 and A-F -- no colons or other characters.
-
- ---------------
-
- /* HEX.C translates the standard input into hexadecimal notation and sends
- * the result to standard output.
- * Usage: hex < foo.exe > foo.hex
- * Christine M. Gianone, CUCCA, October 1986
- * Modified Feb 89 to work right with Microsoft C on the PC.
- */
-
- #include <stdio.h> /* For EOF symbol */
- #ifdef MSDOS
- #include <fcntl.h> /* For MS-DOS O_BINARY symbol */
- #endif
-
- char h[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
- unsigned int c;
- int ctr = 0;
- char a, b;
-
- main() {
- #ifdef MSDOS
- setmode(fileno(stdin),O_BINARY); /* To avoid DOS text-mode conversions */
- #endif
- while ((c = getchar()) != EOF) {
- b = c & 0xF; /* Get low 4 bits */
- a = c / 16; /* and high 4 bits */
- putchar(h[a]); /* Hexify and output them */
- putchar(h[b]);
- ctr += 2; /* Break lines every 72 characters */
- if (ctr == 72) {
- putchar('\n');
- ctr = 0;
- }
- }
- putchar('\n'); /* Terminate final line */
- }
-
- ---------------
-
- /* UNHEX.C - Program to translate a hex file from standard input
- * into an 8-bit binary file on standard output.
- * Usage: unhex < foo.hex > foo.exe
- * Christine M. Gianone, CUCCA, October 1986.
- * Modified Aug 89 to work right with Microsoft C on the PC.
- */
-
- #include <stdio.h> /* Include this for EOF symbol */
- #ifdef MSDOS
- #include <fcntl.h> /* For MS-DOS setmode() symbol */
- #endif
-
- unsigned char a, b; /* High and low hex nibbles */
- unsigned int c; /* Character to translate them into */
- unsigned char decode(); /* Function to decode them */
-
- /* Main program reads each hex digit pair and outputs the 8-bit byte. */
-
- main() {
- #ifdef MSDOS
- setmode(fileno(stdout),O_BINARY); /* To avoid DOS text-mode conversions */
- #endif
- while ((c = getchar()) != EOF) { /* Read first hex digit */
- a = c; /* Convert to character */
- if (a == '\n' || a == '\r') { /* Ignore line terminators */
- continue;
- }
- if ((c = getchar()) == EOF) { /* Read second hex digit */
- fprintf(stderr,"File ends prematurely\n");
- exit(1);
- }
- b = c; /* Convert to character */
- putchar( ((decode(a) * 16) & 0xF0) + (decode(b) & 0xF) );
- }
- exit(0); /* Done */
- }
-
- unsigned char
- decode(x) char x; { /* Function to decode a hex character */
- if (x >= '0' && x <= '9') /* 0-9 is offset by hex 30 */
- return (x - 0x30);
- else if (x >= 'A' && x <= 'F') /* A-F offset by hex 37 */
- return(x - 0x37);
- else { /* Otherwise, an illegal hex digit */
- fprintf(stderr,"\nInput is not in legal hex format\n");
- exit(1);
- }
- }
-
- ------------------------------
-
-